# coding = utf-8
# @Time    : 2024-07-24  11:24:26
# @Author  : zhaosheng@nuaa.edu.cn
# @Describe: Use pandoc -> 1. convert markdown to docx; 2. convert markdown to pdf; 3. convert latex to pdf; 4. convert docx to pdf

import os
import sys
import subprocess
import re

def preprocess_md(md_file):
    # read md_file and replace \r\n- to \r\n\r\n-
    with open(md_file, 'r', encoding='utf-8') as f:
        content = f.read()
    if "\r\n-" in content:
        content = re.sub(r'\r\n-', r'\r\n\r\n-', content)
    else:
        content = re.sub(r'\n-', r'\n\n-', content)
    # 如果存在 ```markdown ``` 则利用re从里面提取出markdown内容
    if "```markdown" in content:
        content = re.sub(r'```markdown\n(.*?)```', r'\1', content
                            , flags=re.DOTALL)
        
    with open(md_file, 'w', encoding='utf-8') as f:
        f.write(content)

def md2docx(md_file, docx_file,template=None):
    # preprocess
    preprocess_md(md_file)
    if template:
        cmd = 'pandoc -s %s --reference-doc=%s -o %s' % (md_file, template, docx_file)
    else:
        cmd = 'pandoc -s %s -o %s' % (md_file, docx_file)
    subprocess.call(cmd, shell=True)
    if os.path.exists(docx_file):
        print('Convert %s to %s successfully!' % (md_file, docx_file))
        return True
    else:
        print('Convert %s to %s failed!' % (md_file, docx_file))
        return False
    

def md2pdf(md_file, pdf_file):
    cmd = 'pandoc -s %s -o %s' % (md_file, pdf_file)
    subprocess.call(cmd, shell=True)
    if os.path.exists(pdf_file):
        print('Convert %s to %s successfully!' % (md_file, pdf_file))
        return True
    else:
        print('Convert %s to %s failed!' % (md_file, pdf_file))
        return False
    

def latex2pdf(latex_file, pdf_file):
    cmd = 'pdflatex %s' % latex_file
    subprocess.call(cmd, shell=True)
    if os.path.exists(pdf_file):
        print('Convert %s to %s successfully!' % (latex_file, pdf_file))
        return True
    else:
        print('Convert %s to %s failed!' % (latex_file, pdf_file))
        return False
    
def docx2pdf(docx_file, pdf_file):
    cmd = 'pandoc -s %s -o %s' % (docx_file, pdf_file)
    subprocess.call(cmd, shell=True)
    if os.path.exists(pdf_file):
        print('Convert %s to %s successfully!' % (docx_file, pdf_file))
        return True
    else:
        print('Convert %s to %s failed!' % (docx_file, pdf_file))
        return False
    
if __name__ == '__main__':
    md_file = 'test.md'
    docx_file = 'test2.docx'
    pdf_file = 'test.pdf'
    md2docx(md_file, docx_file, template='../assest/template.docx')
